package com.dyh.quickdemozwei.daqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * @Author: yhdong
 * @Date: 2021/9/30 16:36
 */
@Slf4j
public class DyhCountSynchronizer extends AbstractQueuedSynchronizer {



//    private final int PENDING = 1;
//    private final int FREE = 1;

    int max;

    DyhCountSynchronizer(int count){
        setState(count);
        this.max = count;
    }

    public int getCount(){
        return getState();
    }

    @Override
    protected boolean tryAcquire(int arg) {
        int count = getState();
        if (count==0)
            return false;
        return compareAndSetState(count,count-arg);
    }


    @Override
    protected boolean tryRelease(int arg) {
        int count = getState();
        if (getState()<max){
            return compareAndSetState(count, count + arg);
        }
        return false;
    }

//    public static void main(String[] args) throws InterruptedException {
//        Dsync dsync = new Dsync(3);
//
//        Thread t1= new Thread(()->{
//            for (int i=0;i<5;i++){
//                dsync.acquire(1);
//                log.info("{} 获取成功",Thread.currentThread().getName());
//            }
//        });
//
////        Thread t2 = new Thread(()->{
////            dsync.release(1);
////            log.info("{} 释放成功",Thread.currentThread().getName());
////
////        });
//
//        t1.start();
//       // t2.start();
//        Thread.sleep(1700L);
//
//        log.info("{} 准备释放",Thread.currentThread().getName());
//        dsync.release(2);
//        log.info("{} 释放成功",Thread.currentThread().getName());
//
//
//
//
//    }

}
